import React, { useState, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom'
import { SearchOutlined } from '@ant-design/icons';
import { Button, Input, Space, Table, Modal } from 'antd';
import Highlighter from 'react-highlight-words';
import { useHistory } from 'react-router-dom';
import { openNotification_util, checkdatavalid_util, fetchsync_util, useCallbackState, dealnullorundenfined } from '../util/util.js'
const { Search } = Input;
var storage = window.localStorage;

const Popup_table_hooks_mx = (props) => {
  const history = useHistory();
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const searchInput = useRef(null);
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [selectedRowsmx, setselectedRowsmx] = useState([])
  const [selectedRowKeysmx, setselectedRowKeysmx] = useState([])
  const [mxdata, setmxdata] = useState([])
  const [tabledata, settabledata] = useState([])
  const [viewname, setviewname] = useState(props.viewname)
  const [viewmxname, setviewmxname] = useState(props.viewmxname)
  const [inputvalue, setinputvalue] = useState(props.inputvalue)
  const [ifshow, setifshow] = useState(false)

  const rowSelection = {
    selectedRowKeys: selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      var newselectedRowsmx = selectedRowsmx.filter(item => {
        var temp = 0
        selectedRows.forEach(mainitem => {
          mainitem.id == item.mainid ? temp++ : 1;
        })
        if (temp == 0) { return false; }
        else { return true; }
      })
      const newselectedRowskeymx = newselectedRowsmx.map(item => item.key)
      setselectedRowKeysmx(newselectedRowskeymx)
      setselectedRowsmx(newselectedRowsmx)
      setselectedRows(selectedRows)
      setselectedRowKeys(selectedRowKeys)
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      // Column configuration not to be checked
      name: record.name,
    }),
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE]
  };

  const rowSelectionmx = {
    selectedRowKeys: selectedRowKeysmx,
    onChange: (selectedRowKeysmx, selectedRowsmx) => {
      setselectedRowsmx(selectedRowsmx)
      setselectedRowKeysmx(selectedRowKeysmx)
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      // Column configuration not to be checked
      name: record.name,
    }),
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE]
  };

  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };
  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText('');
  };

  //row双击s
  const onRowSelect = (record, index) => {
    return {
      onDoubleClick: (e) => {
        // //console.log(selectedRowKeys)
      }
    }
  };

  const getColumnSearchProps = (dataIndex, title) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
      <div
        style={{
          padding: 8,
        }}
        onKeyDown={(e) => e.stopPropagation()}
      >
        <Input
          ref={searchInput}
          placeholder={`搜索${title}`}
          value={selectedKeys[0]}
          onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{
            marginBottom: 8,
            display: 'block',
          }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{
              width: 90,
            }}
          >
            搜索
          </Button>
          <Button
            onClick={() => clearFilters && handleReset(clearFilters)}
            size="small"
            style={{
              width: 90,
            }}
          >
            重置
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              confirm({
                closeDropdown: false,
              });
              setSearchText(selectedKeys[0]);
              setSearchedColumn(dataIndex);
            }}
          >
            过滤
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              close();
            }}
          >
            关闭
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      <SearchOutlined
        style={{
          color: filtered ? '#1890ff' : undefined,
        }}
      />
    ),
    onFilter: (value, record) =>
      record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
    onFilterDropdownOpenChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current ? searchInput.current.select() : 1, 100);
      }
    },
    render: (text) =>
      searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{
            backgroundColor: '#ffc069',
            padding: 0,
          }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ''}
        />
      ) : (
        text
      ),
  });

  const colnumsorigin = props.tablecolnum
  const columns = colnumsorigin.map(item => {
    return {
      title: item.title,
      dataIndex: item.key,
      key: item.key,
      ...getColumnSearchProps(item.key, item.title),

    }
  })

  const mxcolnumsorigin = props.mxtablecolnum
  const mxcolumns = mxcolnumsorigin.map(item => {
    return {
      title: item.title,
      dataIndex: item.key,
      key: item.key,
      ...getColumnSearchProps(item.key, item.title),

    }
  })



  //加载表单数据
  const querytabledata = async () => {
    let rtdata = await fetchsync_util("/admin/qbmes_new/getpopupview", 'POST', { viewname: viewname }, "json")
    rtdata.rtstatus ? settabledata(dealnullorundenfined(rtdata.resultdata)) : 1
  }

  //加载明细表单数据
  const querymxtabledata = async (selectedRows) => {
    let rtdata = await fetchsync_util("/admin/qbmes_new/getpopupview_mainid", 'POST',
      { viewname: viewmxname, selectedRows: selectedRows }, "json")
    rtdata.rtstatus ? setmxdata(dealnullorundenfined(rtdata.resultdata)) : 1
  }




  useEffect(() => {
    setinputvalue(props.inputvalue)
  }, [props.inputvalue])



  useEffect(() => {
    selectedRows.length != 0 ? querymxtabledata(selectedRows) : "";
  }, [selectedRows])

  useEffect(() => {
    setselectedRowsmx([])
    setselectedRowKeysmx([])
    setselectedRows([])
    setselectedRowKeys([])
    querytabledata();

  }, [ifshow])


  //送回数据
  const sendbackdata = async () => {
    if (selectedRows.length == 0) { openNotification_util("未选择数据") }
    else {
      props.handlechange({ selectedRowsmx, selectedRows })
      setifshow(false)
    }

  }


  return (
    <div >
      <Input style={{ width: "95%", backgroundColor: "#F2F7FF" }} placeholder={props.placeholder} value={inputvalue} onClick={() => {
        setifshow(true)

      }} />
      <Modal open={ifshow} destroyOnClose={true} width="95vw" footer={null} style={{
        backgroundColor: "rgba(0,0,0,0.8)", height: "100vh", left: "0%", top: "0%", zIndex: "1050"
      }}
        bodyStyle={{ width: "95vw", height: "90vh", marginTop: "5vh", borderRadius: "8px", boxShadow: "0 8px 32px rgba(0,0,0,0.3)" }}
      >
        <div style={{ position: "relative", backgroundColor: "white", height: "100%", width: "100%", overflowY: "auto", borderRadius: "8px" }}>
          <br />
          <Button style={{ position: "absolute", left: "1rem", top: '0' }} type="" onClick={() => {
            setifshow(false)
          }}> 关闭</Button>&nbsp;

          <br />

          <Table columns={columns} dataSource={tabledata} style={{ width: "96%", height: "56vh" }}
            size="small"
            title={() => { return <div style={{ fontWeight: "400", fontSize: "14px", textAlign: "left" }}>{props.popup_maintitle}</div> }}
            onRow={onRowSelect}
            rowSelection={{
              type: "checkbox",
              ...rowSelection,
            }}
            className="custom-table-styles" />

          <Button style={{ position: "absolute", left: "1rem" }} type="primary" onClick={sendbackdata}>返回数据 </Button>&nbsp;

          <Table columns={mxcolumns}
            dataSource={mxdata} style={{ width: "96%", height: "60vh", position: "absolute", top: "68vh" }}
            size="small"
            title={() => { return <div style={{ fontWeight: "400", fontSize: "14px", textAlign: "left" }}>{props.popup_mxtitle}</div> }}
            onRow={onRowSelect}
                          rowSelection={{
                type: "checkbox",
                ...rowSelectionmx,
              }}
              className="custom-table-styles" />
        </div>
      </Modal>
    </div>
  )

}


export default Popup_table_hooks_mx


var styles = {
  maincontainer: { height: "90%", width: "99%", backgroundColor: `#F1F1F1` }
}



